package com.whj.service.impl;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.whj.domain.enums.AppHttpCodeEnum;
import com.whj.domain.response.ResponseResult;
import com.whj.exception.SystemException;
import com.whj.service.UploadService;
import com.whj.utils.PathUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;




import java.io.FileInputStream;
import java.io.InputStream;

/**
 * @Auther: wanghaijun
 * @Date: 2023/5/26 - 05 - 26 - 19:45 
 * @Description: com.whj.com.whj.service.impl
 */

@Service
public class UploadServiceImpl implements UploadService {

    @Value("${oss.accessKey}")
    private String accessKey;

    @Value("${oss.secretKey}")
    private String secretKey;

    @Value("${oss.bucket}")
    private String bucket;


    @Override
    public ResponseResult uploadImg(MultipartFile img) {

        //判断文件类型
        //获取原始文件名
        String originalFilename = img.getOriginalFilename();
        if (!originalFilename.endsWith(".png") && !originalFilename.endsWith(".jpg")){
            throw new SystemException(AppHttpCodeEnum.FILE_TYPE_ERROR);
        }
        // 判断成功上传操作到OSS
        String url = OSSUpload(img);
        System.out.println("url = " + url);
        return ResponseResult.okResult(url);
    }

    public String OSSUpload(MultipartFile multipartFile){
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.autoRegion());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
        //...其他参数参考类注释

        UploadManager uploadManager = new UploadManager(cfg);
        //...生成上传凭证，然后准备上传
//        String accessKey = "LMBrzkSAYX9WlZffXsDg5AR5dXuZlCEn3rRX3fui";
//        String secretKey = "OHnw6lqZNHEYGi0Fbv0bpMa-j2PCDQuPx1D6ZWgL";
//        String bucket = "whjblog";

        //默认不指定key的情况下，以文件内容的hash值作为文件名
        // 根据日期生成路径
        String filePath = PathUtils.generateFilePath(multipartFile.getOriginalFilename());
        String key = filePath;

        try {
            InputStream inputStream = multipartFile.getInputStream();
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);

            try {
                Response response = uploadManager.put(inputStream,key,upToken,null, null);
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                System.out.println(putRet.key);
                return "http://image.haijun.icu/"+putRet.key;
            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println(r.toString());
                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore
                }
            }
        } catch (Exception ex) {
            //ignore
        }
        return "wwww";
    }
}
